package com.atguigu.day3;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo {
    //v1 多线程不使用原子类AtomicInteger保证线程安全（基本数据类型+synchronized）
    private int number = 0;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        number++;
    }

    //v2多线程使用原子类AtomicInteger保证线程安全
    private AtomicInteger atomicInteger = new AtomicInteger();//初始值为0

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
//        atomicInteger.incrementAndGet();
        atomicInteger.getAndIncrement();
    }

    /*案例：100个线程，每个线程加100次，求最后的number值*/
    public static void main(String[] args) throws InterruptedException {
        CASDemo casDemo = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);


        for (int i = 1; i <= 100; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 100; j++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                //代码执行到此说明某个线程做完了加100次
                countDownLatch.countDown();

            }, String.valueOf("t" + i)).start();
        }
//        TimeUnit.MILLISECONDS.sleep(10);
        countDownLatch.await();
        System.out.println("V1多线程不使用原子类:number=" + casDemo.getNumber());
        System.out.println("V2多线程使用原子类:number=" + casDemo.getAtomicInteger().get());
    }


    public static void helloCAS() {
        AtomicInteger atomicInteger = new AtomicInteger(5);
        System.out.println(atomicInteger.compareAndSet(5, 620) + "\t" + atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(5, 888) + "\t" + atomicInteger.get());
    }
}
